package com.fcc.wfly.base.controller;

import com.fcc.wfly.common.domain.RestApiRequestTrack;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RestApiLogger {

	public static final String HEADER_DATE = "Date";
	public static final String HEADER_CONTENT_TYPE = "Content-Type";
	public static final String HEADER_CONTENT_LENGTH = "Content-Length";
	public static final String HEADER_USER_AGENT = "User-Agent";
	public static final String HEADER_CACHE_CONTROL = "Cache-Control";
	public static final String HEADER_LANGUAGE = "Accept-Language";
	public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
	public static final String HEADER_COOKIE = "Cookie";

	private static SimpleDateFormat DATEFORMART_LOG = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private String apiName = null;

	private HttpServletRequest request = null;

	private JSONObject requestParameter = new JSONObject();

	private JSONObject requestHeader = new JSONObject();

	private Date beginDate = new Date();

	private RestApiLogger() {
	}

	private RestApiLogger(String apiName, HttpServletRequest request) {
		this.apiName = apiName;
		this.request = request;
	}

	public static RestApiLogger begin(String apiName, HttpServletRequest request) {
		RestApiLogger apiLogger = new RestApiLogger(apiName, request);
		return apiLogger;
	}

	public void addParamter(String key, Object value) {
		requestParameter.put(key, value);
	}

	public RestApiRequestTrack end() {
		// parse header
		requestHeader.put(HEADER_DATE, request.getHeader(HEADER_DATE));
		requestHeader.put(HEADER_LANGUAGE, request.getHeader(HEADER_LANGUAGE));
		requestHeader.put(HEADER_ACCEPT_ENCODING, request.getHeader(HEADER_ACCEPT_ENCODING));
		requestHeader.put(HEADER_COOKIE, request.getHeader(HEADER_COOKIE));
		requestHeader.put(HEADER_CONTENT_TYPE, request.getHeader(HEADER_CONTENT_TYPE));
		requestHeader.put(HEADER_USER_AGENT, request.getHeader(HEADER_USER_AGENT));
		requestHeader.put(HEADER_CONTENT_LENGTH, request.getHeader(HEADER_CONTENT_LENGTH));
		requestHeader.put(HEADER_CACHE_CONTROL, request.getHeader(HEADER_CACHE_CONTROL));
		// create domain
		RestApiRequestTrack track = new RestApiRequestTrack();
		track.setApiName(apiName);
		track.setClientId(request.getRemoteAddr());
		track.setRequestParameter(requestParameter.toString());
		track.setRequestHeader(requestHeader.toString());
		track.setRequestTime(DATEFORMART_LOG.format(beginDate));
		track.setResponseTime(DATEFORMART_LOG.format(new Date()));
		track.setInsertTime(DATEFORMART_LOG.format(new Date()));
		return track;
	}

}